package com.pig4cloud.pig.auth.endpoint;

import com.pig4cloud.pig.auth.properties.ImageCodeProperties;
import com.pig4cloud.pig.common.core.constant.CacheConstants;
import com.pig4cloud.pig.common.core.constant.SecurityConstants;
import com.pig4cloud.pig.common.security.annotation.Inner;
import io.springboot.captcha.ArithmeticCaptcha;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.awt.*;
import java.io.File;
import java.util.concurrent.TimeUnit;

/**
 * 验证码相关的接口
 *
 * @author lengleng
 * @date 2022/6/27
 */
@Inner(false)
@RestController
@RequestMapping("/code")
@RequiredArgsConstructor
public class ImageCodeEndpoint {

	private static final Integer DEFAULT_IMAGE_WIDTH = 100;

	private static final Integer DEFAULT_IMAGE_HEIGHT = 40;

	private final RedisTemplate redisTemplate;

	@Resource
	private final ImageCodeProperties imageCodeProperties;

	/**
	 * 创建图形验证码
	 */
	@SneakyThrows
	@GetMapping("/image")
	public void image(String randomStr, HttpServletResponse response) {
		ArithmeticCaptcha captcha = new ArithmeticCaptcha(DEFAULT_IMAGE_WIDTH, DEFAULT_IMAGE_HEIGHT);
		System.out.println("获取字体****************");
		System.out.println(captcha.getFont());
		String path = System.getProperty("java.io.tmpdir");
		System.out.println(path);


		try {

//			todo 把这个目录写在配置文件里面 对于一些及其没有字体文件的就加上这个 字体在对应目录
			System.out.println(imageCodeProperties);
			// 2. 将输入流内容写入到临时文件
			File tempFontFile = new File(imageCodeProperties.getFontpath()); //"/fonts/actionj.ttf"
			if(!tempFontFile.exists()){
				throw new RuntimeException("actionj字体文件不在/fonts/actionj.ttf下面，将使用默认字体");
			}
			// 3. 使用临时文件创建 Font 对象
			Font font = Font.createFont(0, tempFontFile).deriveFont(1, 32.0F);
			captcha.setFont(font);
		}catch (Exception e){
			System.out.println(e);
			System.out.println("ERROR:无法使用验证码字体，将使用默认***************");
		}

		String result = captcha.text();
		redisTemplate.opsForValue()
			.set(CacheConstants.DEFAULT_CODE_KEY + randomStr, result, SecurityConstants.CODE_TIME, TimeUnit.SECONDS);
		// 转换流信息写出
		captcha.out(response.getOutputStream());
	}

}
